<template>
  <div class="sale-management">
    <h2>销售管理</h2>
    <!-- 筛选区 -->
    <el-form :inline="true" class="filter-form">
      <el-form-item label="销售单号">
        <el-input v-model="filters.SaleId" placeholder="请输入销售单号" clearable/>
      </el-form-item>
      <el-form-item label="产品名称">
        <el-input v-model="filters.ProductName" placeholder="请输入产品名称" clearable/>
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input v-model="filters.ProductId" placeholder="请输入产品编号" clearable/>
      </el-form-item>
      <el-form-item label="订单状态">
        <el-select v-model="filters.State" placeholder="请选择状态" style="width: 120px;" clearable >
          <el-option label="已销售" value="1" />
          <el-option label="已取消" value="2" />
          <el-option label="已退货" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table :data="tableData" style="width: 100%; margin-top: 20px;">
      <el-table-column prop="saleId" label="销售单号" />
      <el-table-column prop="productName" label="产品名称"  min-width="130"/>
      <el-table-column prop="productId" label="产品编号" />
      <el-table-column prop="productSpecs" label="产品规格"  min-width="130"/>
      <el-table-column prop="unitId" label="单位" />
      <el-table-column prop="price" label="单价" />
      <el-table-column prop="num" label="数量" />
      <el-table-column prop="total" label="总额" />
      <el-table-column prop="customerId" label="客户编号" />
      <el-table-column prop="customerName" label="客户名称" />
      <el-table-column prop="state" label="状态" :formatter="formatState" />
      <el-table-column prop="madeTime" label="创建时间" :formatter="formatDate" min-width="120" />
      <el-table-column prop="recorded" label="是否入账" :formatter="formatRecorded" />
      <el-table-column prop="refundNum" label="退货" :formatter="formatRecorded" />
       <el-table-column label="操作" min-width="250">
        <template #default="scope">
              <el-button type="text" @click="handleView(scope.row)">查看</el-button>
              <el-button type="text" @click="handleEdit(scope.row)" >编辑</el-button>
              <el-button type="text" v-if="!scope.row.recorded" @click="handleRecord(scope.row)">入账</el-button>
              <el-button type="text" style="color: #ff4d4f;" @click="handleDelete(scope.row)">删除</el-button>
              <el-button
                v-if="scope.row.state === 1"
                type="primary"
                size="small"
                @click="handleSaleRefund(scope.row)"
              >退货</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pages.PageIndex"
        v-model:page-size="pages.PageSize"
        :total="pages.totalCount"
        :page-sizes="[10, 15, 20, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>


   <el-dialog v-model="dialogVisible" title="销售订单" width="1200px" :close-on-click-modal="false">
       <div class="dialog-content">
      <div class="order-header">
        <div class="order-info">
          <div class="info-item"><span class="label">订单号：</span>{{ productInfo?.saleId }}</div>
          <div class="info-item"><span class="label">状态：</span>{{ formatStates(productInfo?.state) }}</div>
        </div>
        
        <div class="order-info">
          <div class="info-item"><span class="label">制单人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">制单日期：</span>{{ formatDates(productInfo?.madeTime) }}</div>
          <div class="info-item"><span class="label">是否入账：</span>{{ productInfo?.recorded ? '是' : '否' }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">客户编号：</span>{{ productInfo?.customerId }}</div>
          <div class="info-item"><span class="label">客户名称：</span>{{ productInfo?.customerName }}</div>
          <div class="info-item"><span class="label">退货状态：</span>{{ productInfo?.refundNum ? '是' : '否' }}</div>
        </div>

        <div class="order-info">
          <div class="info-item"><span class="label">联系人：</span>{{ productInfo?.contactPerson }}</div>
          <div class="info-item"><span class="label">电话：</span>{{ productInfo?.phone }}</div>
          <div class="info-item"><span class="label">备注：</span>{{ productInfo?.description }}</div>
        </div>
      </div>

        <el-table :data="productInfo?.productDetails || []" border style="margin-top: 20px;">
          <el-table-column prop="productCode" label="产品编码" width="120"/>
          <el-table-column prop="productName" label="产品名称" width="250"/>
          <el-table-column prop="productSpecs" label="规格" width="120"/>
          <el-table-column prop="unitName" label="单位" width="80"/>
          <el-table-column prop="num" label="数量" width="80"/>
          <el-table-column prop="price" label="单价" width="100"/>
          <el-table-column prop="total" label="总额" width="100"/>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 销售退货弹窗 -->
    <el-dialog v-model="saleRefundDialogVisible" title="销售退货" width="800px">
      <el-form :model="saleRefundForm">
        <el-form-item label="退货单号">
          <el-input v-model="saleRefundForm.saleRefundNum" disabled />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input v-model="saleRefundForm.productName" disabled />
        </el-form-item>
        <el-form-item label="产品编号">
          <el-input v-model="saleRefundForm.productId" disabled />
        </el-form-item>
        <el-form-item label="产品规格">
          <el-input v-model="saleRefundForm.productSpecs" disabled />
        </el-form-item>
        <el-form-item label="单位">
          <el-input v-model="saleRefundForm.unitid" disabled />
        </el-form-item>
        <el-form-item label="单价">
          <el-input v-model="saleRefundForm.price" disabled />
        </el-form-item>
        <el-form-item label="退货数量">
          <el-input-number v-model="saleRefundForm.refundNum" :min="1" />
        </el-form-item>
        <el-form-item label="退货原因">
          <el-input v-model="saleRefundForm.refundReason" />
        </el-form-item>
        <!-- 可根据需要添加更多字段 -->
      </el-form>
      <template #footer>
        <el-button @click="saleRefundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitSaleRefund">保存</el-button>
      </template>
    </el-dialog>

</template>

<script lang="ts" setup>
import axios from 'axios'
import { onMounted, reactive, ref, watch } from 'vue'

import moment from 'moment';

onMounted(()=>{
  onSearch();
})

const filters = reactive({
  ProductName: '',
  ProductId: '',
  SaleId: '',
  State: ''
})

const pages=reactive({
  PageIndex: 1,
  PageSize: 15,
  totalPage: 0,
  totalCount: 0
})

watch(pages,()=>{
  onSearch();
})

const tableData = ref([])
import Purchase from '@/http/PurSale';
const onSearch=() => {
  http.get("/scmreadconsul/api/Sale/getSale",{
    params:{
      ProductName: filters.ProductName,
      ProductId: filters.ProductId,
      SaleId: filters.SaleId,
      State: filters.State,
      PageIndex: pages.PageIndex,
      PageSize: pages.PageSize
    }
  }).then(res=>{
    tableData.value = res.data.items;
    pages.totalCount = res.data.totalCount;
    pages.totalPage = res.data.totalPage;
  })
}

// 分页事件处理
const handleSizeChange = (val: number) => {
  pages.PageSize = val;
  pages.PageIndex = 1; // 重置为第一页
}

const handleCurrentChange = (val: number) => {
  pages.PageIndex = val;
}

// 格式化日期
const formatDate = (row: any, column: any, cellValue: any) => {
  if (!cellValue) return '';
  return moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
}

// 格式化是否入账
const formatRecorded = (row: any, column: any, cellValue: any) => {
  return cellValue ? '是' : '否';
}

// 格式化状态
const formatState = (row: any, column: any, cellValue: any) => {
  switch(cellValue){
    case 1: return '已销售';
    case 2: return '已取消';
    case 3: return '已退货';
    default: return '未知状态';
  }
}
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

import http from '@/http/axiosHelper';
import Check from '@/http/Check';
const router=useRouter();
const handleEdit = (row: any) => {
  router.push({ 
    path: '/updsale', 
    query: { id: row.id } 
  });
};

// 删除操作
const handleDelete = async (row: any) => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      `确定要删除销售单 "${row.id}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    // 调用删除接口
    const response = await http.put('/scmwriteconsul/api/Sale/DelSale', {
      id: row.id
    });

    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || '删除成功');
      onSearch(); // 刷新采购列表
    } else {
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消删除
      return;
    }
    console.error('删除接口调用失败:', error);
    ElMessage.error('网络错误，删除操作失败');
  }
};
// 定义产品详情接口
interface ProductDetails {
  productCode: string;
  productName: string;
  productSpecs: string;
  unitName: string;
  num: number;
  price: number;
  total: number;
 
}

// 定义采购信息接口
interface ProductInfo {
  id:number;
  saleId: string;
  state: number;
  contactPerson: string;
  madeTime: string;
  recorded: boolean;
  customerId: string;
  customerName: string;
  refundNum: string;
  phone: string;
  description: string;
  productDetails: ProductDetails[];
}
// 对话框相关变量
const dialogVisible = ref(false);
const productInfo = ref<ProductInfo>({} as ProductInfo);
const dialogVisibles=ref(false);
// 查看详情
const handleView = async (row:any) => {
  try {
    // 先获取采购信息
    const purchaseResponse = await http.get("/scmreadconsul/api/Sale/GetSaleOne", {
      params: {
        Id: row.id
      }
    });
    // 再获取产品详情
    const productResponse = await http.get("/scmreadconsul/api/Purchases/LookProduct", {
      params: {
        ProductId: row.productId
      }
    });

    productInfo.value = {
      id:row.id,
      ...purchaseResponse.data.data,
      // 如果产品详情是对象则转为数组
      productDetails: Array.isArray(productResponse.data.data) ? productResponse.data.data : [productResponse.data.data]
    };
    dialogVisible.value = true;
  } catch (error) {
    ElMessage.error('请求数据时发生错误');
    console.error('Data request error:', error);
  }
};
const formatStates = (cellValue: any) => {
  switch(cellValue){
    case 1: return '已销售';
    case 2: return '已取消';
    case 3: return '已退货';
    default: return '未知状态';
  }
}
// 时间格式化函数
const formatDates = (cellValue: any) => {
  if (!cellValue) return '';
  return moment(cellValue).format('YYYY-MM-DD HH:mm:ss');
}

// 入账操作
const handleRecord = async (row: any) => {
  try {
    // 调用入账接口
    const response = await http.put('/scmwriteconsul/api/Sale/UpdRecordedSale', {
      id: row.id,
      recorded: true
    });

    if (response.data.code === 200) {
      ElMessage.success(response.data.msg || '入账成功');
      onSearch(); // 刷新采购列表
    } else {
      ElMessage.error(response.data.msg || '入账失败');
    }
  } catch (error) {
    console.error('入账接口调用失败:', error);
    ElMessage.error('网络错误，入账操作失败');
  }
};

const saleRefundDialogVisible = ref(false);
const saleRefundForm = reactive<any>({
  saleRefundNum: '', // 退货单号，自动生成
  productName: '',
  productId: 0,
  productSpecs: '',
  unitid: 0,
  price: 0,
  refundNum: 1,
  total: 0,
  saleId: '',
  customerId: 0,
  customerName: '',
  createName: '',
  state: 0,
  madeName: 0,
  madeTime: '',
  createTime: '',
  isDel: false,
  refundReason: ''
});

function generateSaleRefundNum(): string {
  const now = new Date();
  const pad = (n: number) => n.toString().padStart(2, '0');
  return `OS_${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}${Math.floor(Math.random() * 1000)}`;
}

function handleSaleRefund(row: any) {
  saleRefundForm.saleRefundNum = generateSaleRefundNum();
  saleRefundForm.productName = row.productName;
  saleRefundForm.productId = row.productId;
  saleRefundForm.productSpecs = row.productSpecs;
  saleRefundForm.unitid = row.unitid;
  saleRefundForm.price = row.price;
  saleRefundForm.refundNum = 1;
  saleRefundForm.total = row.price; // 默认退1件
  saleRefundForm.saleId = row.saleId;
  saleRefundForm.customerId = row.customerId;
  saleRefundForm.customerName = row.customerName;
  saleRefundForm.createName = row.createName;
  saleRefundForm.state = 0;
  saleRefundForm.madeName = row.madeName;
  saleRefundForm.madeTime = row.madeTime;
  saleRefundForm.createTime = new Date().toISOString();
  saleRefundForm.isDel = false;
  saleRefundForm.refundReason = '';
  saleRefundDialogVisible.value = true;
}

async function submitSaleRefund() {
  try {
    const res = await http.post('/scmwriteconsul/api/SaleRefund/AddSaleRefund', saleRefundForm);
    if (res.data.code === 200) {
      saleRefundDialogVisible.value = false;
      // 可刷新列表等
    } else {
      alert(res.data.msg || '退货失败');
    }
  } catch (e) {
    alert('网络错误');
  }
}
</script>

<style scoped>
.sale-management {
  padding: 24px;
}
.filter-form {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  text-align: center;
}
.el-table .cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.dialog-content {
  padding: 10px;
}

.order-header {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.order-info {
  display: flex;
  margin-bottom: 10px;
}
.info-item {
  flex: 1;
  margin-right: 15px;
  line-height: 2;
}

.label {
  font-weight: bold;
  color: #606266;
}
</style>